import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:syria_sports/core/app_export.dart';

import '../remote/dio_helper.dart';

enum OperationStatus {pending, synced, failed}

class SyncOperation {
  final int operationId;
  final String endpoint;
  final String method;
  final String payload;
  String? status; //"pending", "synced", "failed"
  late OperationStatus state;
  String? errorMessage;
  final DateTime createdAt;
  final DateTime? updatedAt;

  SyncOperation({
    this.operationId = -1,
    required this.endpoint,
    required this.method,
    required this.payload,
    this.status,
    this.errorMessage,
    required this.createdAt,
    this.updatedAt,
  }){
    switch (status){
      case "pending":
        state = OperationStatus.pending;
      case "synced":
        state = OperationStatus.synced;
      case "failed":
        state = OperationStatus.failed;
    }
  }

  factory SyncOperation.fromRawJson(String str) => SyncOperation.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory SyncOperation.fromJson(Map<String, dynamic> json) => SyncOperation(
    operationId: json["operation_id"],
    endpoint: json["endpoint"],
    method: json["method"],
    payload: json["payload"],
    status: json["status"],
    errorMessage: json["error_message"],
    createdAt: DateTime.parse(json["created_at"]),
    updatedAt: json["updated_at"] != null ? DateTime.parse(json["updated_at"]) : null,
  );

  Map<String, dynamic> toJson() => {
    //"operation_id": operationId,
    "endpoint": endpoint,
    "method": method,
    "payload": payload,
    "status": status,
    "error_message": errorMessage,
    "created_at": createdAt.toIso8601String(),
    "updated_at": updatedAt?.toIso8601String(),
  };


  Future<Response<dynamic>?> sendRequest() async {
    // قم بتحديد طريقة الطلب وفقًا لما هو موجود في الـ operation
    final uri = endpoint;
    switch (method) {
      case 'POST':
        var res = await DioHelper.postData(
          url: uri,
          bearerToken: PrefUtils.getToken(),
          data: json.decode(payload),
        );
        return res;
      case 'PUT':
        var res = await DioHelper.putData(
          url: uri,
          bearerToken: PrefUtils.getToken(),
          data: json.decode(payload),
        );
        return res;
      case 'DELETE':
        return null;
      default:
        var res = await DioHelper.getData(
          url: uri,
          bearerToken: PrefUtils.getToken(),
          query: json.decode(payload),
        );
        return res;
    }
  }

}
